package com.itljm.cxrMarket.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itljm.cxrMarket.common.PageResult;
import com.itljm.cxrMarket.common.Result;
import com.itljm.cxrMarket.entity.Categories;
import com.itljm.cxrMarket.service.CategoriesService;
import com.itljm.cxrMarket.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ljm
 * @date 2024/12/13 9:20
 */
@RestController
@RequestMapping("/categories")
@CrossOrigin
public class CategoriesController {
    @Autowired
    private CategoriesService categoriesService;

    // 分页查询
    @RequestMapping("/info")
    public PageResult<Categories> selectPage(Integer page, Integer limit,String categoryName) {
        if (page == null) {
            page = 0;
        }
        if (limit == null) {
            limit = 15;
        }
        Page<Categories> categoriesPage = new Page<>(page, limit);
        QueryWrapper<Categories> wrapper = new QueryWrapper<>();
        wrapper.eq("1", "1");
        if (StringUtils.isNotEmpty(categoryName)) {
            wrapper.like("category_name", categoryName);
        }
        List<Categories> list = categoriesService.selectCategoriesPage(categoriesPage, wrapper);
        return new PageResult<>(list, categoriesPage.getTotal());
    }

    // 查询全部
    @RequestMapping("/list")
    public Result selectAll() {
        List<Categories> list = categoriesService.selectAll();
        if (list == null) {
            return Result.fail("查询失败");
        }
        return Result.ok("查询成功", list);
    }

    // 根据id查询
    @RequestMapping("/info/{id}")
    public Result selectCategoriesById(@PathVariable Integer id) {
        Categories categories = categoriesService.selectCategoriesById(id);
        if (categories == null) {
            return Result.fail("查询失败");
        }else {
            return Result.ok("查询成功", categories);
        }
    }

    // 新增或修改
    @RequestMapping("/save")
    public Result save(@RequestBody Categories categories) {
        boolean b = categoriesService.saveCategories(categories);
        return b ? Result.ok("操作成功") : Result.fail("操作失败") ;
    }

    // 删除
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean b = categoriesService.removeById(id);
        return b ? Result.ok("操作成功") : Result.fail("操作失败");
    }
}
